package com.ergou.easylive.admin.interceptor;

import com.ergou.easylive.admin.properties.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * JWT 拦截器
 *
 * @author Er-Gou
 * @date 2025-09-16 22:55
 */
@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {

    @Resource
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        
        // 检查是否为不需要token验证的路径
        if (isExcludedPath(requestURI)) {
            return HandlerInterceptor.super.preHandle(request, response, handler);
        }

        String token = extractToken(request);
        if (token == null) {
            throw new RuntimeException("token不存在");
        }

        log.info("===================进入Jwt拦截器中===================");
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
    
    /**
     * 检查是否为排除路径
     */
    private boolean isExcludedPath(String requestURI) {
        // 排除的路径列表
        String[] excludedPaths = {
            "/auth/login",
            "/captcha/image",
            "/doc.html",
            "/swagger-ui",
            "/webjars",
            "/swagger-resources",
            "/v3/api-docs",
            "/favicon.ico",
            "/error"
        };
        
        for (String excludedPath : excludedPaths) {
            if (requestURI.startsWith(excludedPath)) {
                return true;
            }
        }
        return false;
    }


    private String extractToken(HttpServletRequest request) {
        String token = request.getHeader(jwtProperties.getRequestHeader());
        if (token == null || "".equals(token)) {
            token = request.getParameter(jwtProperties.getRequestHeader());
        }
        if (token != null && token.startsWith(jwtProperties.getTokenPrefix())) {
            token = token.substring(jwtProperties.getTokenPrefix().length());
        }
        return token;
    }
}
